package cn.mymanagesys.servlet;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@WebServlet("/captcha")
public class CaptchaServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);

        // 获取验证码
        String code = lineCaptcha.getCode();
        // 将验证码存到session
        request.getSession().setAttribute("captcha",code);

        // 将验证码写入 response的输出流中
        // lineCaptcha.write(response.getOutputStream());

        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        lineCaptcha.write(baos);

        byte[] bytes = baos.toByteArray();//转换成字节
        BASE64Encoder encoder = new BASE64Encoder();
        String png_base64 =  encoder.encodeBuffer(bytes);//转换成base64串
        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n

        response.getWriter().write(png_base64);


        // // 关闭输出流
        // response.getOutputStream().flush();
        // response.getOutputStream().close();
    }
}
